<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class Order_model extends MY_Model {

	var $table = 'order';
	private $CI;

	public function __construct() {
		parent::__construct();
		$this->CI = & get_instance();
	}

	public function subsidy($price) {
		$query = $this->db->select('amount')->get_where('subsidy', array(
			'min_consumption <=',
			$price
				), 1);
		$row = $query->row_array();
		return empty($row) ? 0 : $row ['amount'];
	}

	/**
	 * 创建订单
	 *
	 * @param array $orderCreate        	
	 * @param array $order        	
	 * @throws Exception
	 */
	public function create($orderCreate, $order) {
		$orderCreate ['created_at'] = time();
		$orderCreate ['updated_at'] = time();
		$result = $this->db->insert($this->table, $orderCreate);
		if (!$result) {
			throw new Exception ();
		}
		$order_id = $this->db->insert_id();

		$filter = array(
			'sw_product_id',
			'product_id',
			'name',
			'price',
			'number',
			'options'
		);
		$data = array();
		foreach ($order as $val) {
			$tmp = array(
				'order_id' => $order_id,
				'created_at' => time(),
				'updated_at' => time()
			);
			foreach ($filter as $v) {
				$tmp [$v] = $val [$v];
			}
			$data [] = $tmp;
		}
		$rows = $this->db->insert_batch('order_details', $data);
		if ($rows !== count($order)) {
			throw new Exception ();
		}
		return $order_id;
	}

	/**
	 * 获取所有订单
	 */
	public function getOrders($where, $config, $select = 'o.contact_name,o.contact_tel,o.contact_sex,o.contact_address,o.order_num,o.note,') {
		$limit = NULL;
		$offset = NULL;
		$join = NULL;

		if (!empty($config)) {
			foreach ($config as $key => $val) {
				$$key = $val;
			}
		}

		if ($limit && $offset >= 0) {
			$this->db->limit($limit, $offset);
		}

		$this->db->select($select . 'o.id,format(o.total_price/100, 2) total_price,format(o.subsidy/100, 2) subsidy,format(o.netpay/100,2) netpay,o.request_num,o.status,o.created_at,o.pay_time,a.username,a.nickname', false)
				->from($this->table . ' o')
				->join('agent a', 'o.agent_id=a.id', 'left')
				->order_by('o.updated_at desc, o.id desc');

		if (!empty($join)) {
			foreach ($join as $v) {
				$this->db->join($v[0], $v[1], $v[2]);
			}
		}
		if (!empty($where)) {
			foreach ($where as $k => $v) {
				if (is_array($v)) {
					$this->db->where_in($k, $v);
				} else {
					$this->db->where($k, $v);
				}
			}
		}

		$query = $this->db->get();
		$tmp = $query->result_array();
		if (empty($tmp)) {
			return $tmp;
		}
		$tmp1 = array();
		foreach ($tmp as $v) {
			if (array_key_exists('reminder', $v) && ($v['status'] < REST_Controller::PAY_STATUS_PAYED || $v['status'] > REST_Controller::PAY_STATUS_DELIVERING)) {
				$v['reminder'] = REST_Controller::STATUS_ACTIVE;
			}
			if (array_key_exists('comment', $v)) {
				$v['comment'] = ($v['status'] == REST_Controller::PAY_STATUS_FINISH && empty($v['comment'])) ? REST_Controller::STATUS_DELETE : REST_Controller::STATUS_ACTIVE;
			}
			$v ['created_at'] = empty($v ['pay_time']) ? $v ['created_at'] : $v ['pay_time'];
			unset($v ['pay_time']);
			$v ['status_desc'] = $this->lang->line("w1000{$v['status']}");
			if(isset($v['note'])) {
				$v ['note'] = json_decode($v['note']);
			}
			$v ['user_head_img'] = base_url('data/share/upload/head_img/14405938061421.jpg');
			$tmp1 [$v ['id']] = $v;
		}

		$query = $this->db->select('od.product_id,od.order_id,a.img as thumbnail, od.name, od.number, format(od.price/100, 2) price, od.options', false)->from('order_details od')->join('product p', 'od.product_id=p.id', 'left')->join('album a', 'p.thumbnail_id=a.id', 'left')->where_in('order_id', array_keys($tmp1))->get();
		$tmp2 = $query->result_array();

		$data = array();
		foreach ($tmp2 as &$v) {
			$order_id = $v ['order_id'];
			$v ['thumbnail'] = empty($v ['thumbnail']) ? '' : base_url($v ['thumbnail']);
			if (isset($tmp1 [$order_id])) {
				$options = unserialize($v ['options']);
				if (is_array($options)) {
					$options = implode(' ', array_values($options));
				}
				$v ['options'] = $options;
				$v ['price_total'] = $v ['number'] * $v ['price'];
				unset($v ['price']);
				unset($v ['order_id']);
				$tmp1 [$order_id] ['details'] [] = $v;
			}
		}

		return array_values($tmp1);
	}

	/**
	 * 订单详情
	 *
	 * @param number $orderId        	
	 */
	public function orderDetails($orderId, $data = array()) {
		if (empty($data)) {
			$query = $this->db->select('format(o.total_price/100, 2) total_price,format(o.subsidy/100, 2) subsidy,format(o.netpay/100, 2) netpay,o.order_num,format(o.shipping_fee/100, 2) shipping_fee,o.created_at,o.pay_time,o.pay_method,o.contact_name,o.contact_tel,o.contact_address,o.sign_for_code,o.note', false)->from($this->table . ' o')->where(array(
						'o.id' => $orderId
					))->get();
			$data = $query->row_array();
		}
		if (!empty($data)) {
			if (!empty($data['pay_time'])) {
				$data['created_at'] = $data['pay_time'];
			}
			unset($data['pay_time']);
			$data['note'] = json_decode($data['note']);
			$query = $this->db->select('od.product_id,a.img as thumbnail,od.name,od.number,format(od.price/100,2) price,od.options', false)->from('order_details od')->join('product p', 'od.product_id=p.id', 'left')->join('album a', 'p.thumbnail_id=a.id', 'left')->where(array(
						'od.order_id' => $orderId
					))->get();
			$details = $query->result_array();
			foreach ($details as &$v) {
				$v ['thumbnail'] = empty($v ['thumbnail']) ? '' : base_url($v ['thumbnail']);
				$options = unserialize($v ['options']);
				if (is_array($options)) {
					$options = implode(' ', array_values($options));
				}
				$v ['options'] = $options;
				$v ['total_price'] = $v ['price'] * $v ['number'];
				unset($v ['price']);
			}
			$data ['details'] = $details;
		}
		return $data;
	}

	/**
	 * 订单地址是否有效
	 *
	 * @param number $deliveryAddressId        	
	 * @param number $address_id        	
	 */
	public function addressValid($deliveryAddressId, $address_id) {
		$query = $this->db->select(array(
					'oa.tel contact_tel',
					'oa.contactName contact_name',
					'oa.sex contact_sex',
					'concat(a.description, \' \', ae.address, oa.address) contact_address'
				))->from('order_address oa')->join('areas_enabled ae', 'oa.areas_id=ae.id', 'left')->join('areas a', 'ae.district_id=a.id', 'left')->where(array(
					'oa.user_id' => $_SESSION ['uid'],
					'oa.areas_id' => $address_id,
					'oa.id' => $deliveryAddressId
				))->get();
		return $query->row_array();
	}

	/**
	 * 更新支付信息
	 *
	 * @param array $data        	
	 * @param number $orderId        	
	 * @return boolean
	 */
	public function pay($data, $orderId) {
		return $this->update($data, array(
					'id' => $orderId
		));
	}

	/**
	 * 订单状态
	 *
	 * @param number $orderId        	
	 */
	public function orderStatus($orderId) {
		$query = $this->db->select('o.id,format(o.shipping_fee/100,2) shipping_fee,format(o.netpay/100,2) netpay,format(o.subsidy/100,2) subsidy,o.reminder,o.status,c.id as comment,a.username,a.nickname', false)
				->from($this->table . ' o')
				->join('agent a', 'o.agent_id=a.id', 'left')
				->join('comment c', 'o.id=c.order_id and o.user_id=c.user_id', 'left')
				->where(array('o.id' => $orderId))
				->get();
		$data = $query->row_array();
		if (empty($data)) {
			return $data;
		}
		if ($data['status'] < REST_Controller::PAY_STATUS_PAYED || $data['status'] > REST_Controller::PAY_STATUS_DELIVERING) {
			$data['reminder'] = REST_Controller::STATUS_ACTIVE;
		}
		if ($data['status'] == REST_Controller::PAY_STATUS_FINISH && empty($data['comment'])) {
			$data['comment'] = REST_Controller::STATUS_DELETE;
		} else {
			$data['comment'] = REST_Controller::STATUS_ACTIVE;
		}
		$data ['user_head_img'] = base_url('data/share/upload/head_img/14405938061421.jpg');
		$query = $this->db->select('title, short_desc, type, created_at')->get_where('order_log', array(
			'order_id' => $orderId
		));
		$data['list'] = $query->result_array();
		return $data;
	}

	/**
	 * 订单日志
	 *
	 * @param number $orderId        	
	 * @param number $descId        	
	 * @param number $type        	
	 * @return boolean
	 */
	public function log($orderId, $descId, $short_desc = '', $type = 1) {
		$status = $descId;
		$descId += 10000;
		$data = array(
			'order_id' => $orderId,
			'title' => $this->lang->line("w{$descId}"),
			'short_desc' => $short_desc,
			'status' => $status . '',
			'type' => $type . '',
			'created_at' => time()
		);
		return $this->db->insert('order_log', $data);
	}

	public function getOrder($orderId) {
		$query = $this->db->select('o.id,format(o.total_price/100, 2) total_price,format(o.subsidy/100, 2) subsidy,format(o.netpay/100, 2) netpay,o.status,o.address_id,o.request_num,o.ext_order_num,o.order_num,format(o.shipping_fee/100, 2) shipping_fee,o.created_at,o.pay_time,o.pay_method,o.contact_name,o.contact_tel,o.contact_address,o.sign_for_code,o.note,aa.status as storeStatus', false)
				->from($this->table . ' o')
				->join('areas_enabled aa', 'o.address_id=aa.id', 'left')
				->where(array('o.id' => $orderId))
				->limit(1)
				->get();
		return $query->row_array();
	}

	public function close($orderId, $uid = '') {
		try {
			$this->db->trans_begin();
			if (is_array($orderId)) {
				$this->db->where_in('order_id', $orderId);
			} else {
				$this->db->where('order_id', $orderId);
			}

			$query = $this->db->select('sw_product_id as id,number')
					->from('order_details')
					->get();
			$rows = $query->result_array();
			if (!empty($rows)) {
				foreach ($rows as $v) {
					$this->db->set('stock', "stock+{$v['number']}", FALSE);
					$this->db->where('id', $v['id']);
					$this->db->update('sm_warehouse_stock');
				}
			}
			$data = array(
				'status' => REST_Controller::PAY_STATUS_CLOSE,
				'updated_at' => time(),
			);
			$where = array(
				'id' => $orderId,
			);
			if (!empty($uid)) {
				$where['user_id'] = $uid;
				$where['status'] = REST_Controller::PAY_STATUS_UNPAY;
			}
			$this->db->update($this->table, $data, $where);
			if (!$this->db->affected_rows()) {
				throw new Exception('Syntax error');
			}
			if ($this->db->trans_status() === FALSE) {
				throw new Exception('Syntax error');
			}
			$this->db->trans_commit();
			return true;
		} catch (Exception $e) {
			$this->db->trans_rollback();
			return false;
		}
	}

	/**
	 * 取得个人指数
	 */
	public function PersonZS($uid) {
		$result = $this->db->select('total_price,pay_time')->from($this->table)->where(array(
					'agent_id' => $uid,
					'status >' => REST_Controller::PAY_STATUS_UNPAY
				))->get()->result_array();

		$dayNum = 0; // 当日接单数
		$monthNum = 0; // 当月接单数
		$totalPrice = 0; // 当月总金额

		foreach ($result as $v) {
			if ($v ['pay_time'] > strtotime(date('Y-m-d', time()))) {
				$dayNum ++;
			}

			if ($v ['pay_time'] > strtotime(date('Y-m', time()))) {
				$monthNum ++;
				$totalPrice += $v ['total_price']; // 当月总金额
			}
		}

		$data = array(
			'dayNum' => $dayNum,
			'monthNum' => $monthNum,
			'totalPrice' => $totalPrice
		);

		return $data;
	}

	/**
	 * 取得店铺指数
	 */
	public function ShopZS($address_id) {
		// 获取订单
		$result = $this->db->select('address_id,pay_method,status,total_price,pay_time')->from($this->table)->where(array(
					'status >' => REST_Controller::PAY_STATUS_UNPAY
				))->where_in('address_id', $address_id)->get()->result_array();

		$dayNum = 0; // 当日接单数
		$monthNum = 0; // 当月接单数
		$totalMonPrice = 0; // 当月总金额
		$totalNum = 0; // 总成交笔数
		$onlinePayNum = 0; // 在线支付笔数
		$codPayNum = 0; // 货到付款笔数cash on delivery (COD)(百度百科)
		$totalPrice = 0; // 全部总金额

		foreach ($result as $v) {
			
			if ($v ['pay_time'] > strtotime(date('Y-m-d', time()))) {
				
				//已签收或者已完成的
				if($v['status'] == 6 || $v['status'] == 7){
					$dayNum ++;
				}
				
			}

			if ($v ['pay_time'] > strtotime(date('Y-m', time()))) {
				
				//已签收或者已完成的
				if($v['status'] == 6 || $v['status'] ==7 )
				{
					$monthNum ++;
					$totalMonPrice += $v ['total_price']; // 当月总金额
				}
			}

			//状态是已完成
			if ($v ['status'] == 7) {
				$totalNum ++;
				$totalPrice += $v ['total_price'];
			}

			//状态是已完成与支付方式是1和2的
			if ($v ['status'] == 7 && ($v['pay_method'] == 1 || $v['pay_method'] = 2)) {
				$onlinePayNum ++;
			}

			if ($v ['status'] == 3 && $v['pay_method'] == 3) {
				$codPayNum ++;
			}
		}

		$data = array(
			'dayNum' => $dayNum,
			'monthNum' => $monthNum,
			'totalMonPrice' => $totalMonPrice / 100,
			'totalNum' => $totalNum,
			'onlinePayNum' => $onlinePayNum,
			'codPayNum' => $codPayNum,
			'totalPrice' => $totalPrice
		);

		return $data;
	}

	/**
	 * 获取营业统计(按照时间段进行统计)
	 */
	public function getShopReport($address_id, $timeStart, $timeEnd) {
		// 获取订单
		$result = $this->db->select('address_id,pay_method,status,total_price,pay_time')->from($this->table)->where(array(
					'status >' => REST_Controller::PAY_STATUS_UNPAY
				))->where_in('address_id', $address_id)->get()->result_array();


		$totalNum = 0; // 该时间段下的总成交笔数
		$onlinePayNum = 0; // 该时间段下的在线支付笔数
		$codPayNum = 0; // 该时间段下的货到付款笔数cash on delivery (COD)(百度百科)
		$totalPrice = 0; // 该时间段下的全部总金额


		$sql = '';
		foreach ($result as $v) {

			//在这个时间段下才统计
			if ($v ['pay_time'] >= strtotime($timeStart) && $v ['pay_time'] < (strtotime($timeEnd) + 60 * 60 * 24)) {
				$totalNum++;
				$totalPrice+= $v ['total_price'];
				//状态是已完成与支付方式是1和2的
				if ($v ['status'] == 7 && ($v['pay_method'] == 1 || $v['pay_method'] = 2)) {
					$onlinePayNum ++;
				}
				if ($v ['status'] == 3 && $v['pay_method'] == 3) {
					$codPayNum ++;
				}
			}
		}

		$data = array(
			'totalNum' => $totalNum,
			'onlinePayNum' => $onlinePayNum,
			'codPayNum' => $codPayNum,
			'totalPrice' => $totalPrice / 100
		);

		return $data;
	}

}
